18. OnClickListener vs onClick

OnClickListener vs onClick

You might be wondering why we're going through all the trouble of creating an anonymous subclass of OnClickListener and attaching it to a view, when we already know how to use the onClick XML attribute from from back in Android Basics: User Input. Why write something terrifying like:

// In onCreate() in the Activity
Button button = (Button) findViewById(R.id.ze_button);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        doSomeStuff();
    }
});

When we could do something much cleaner like:

android:onClick="myListener" // This is in the XML layout

public void myListener(View view){ // This is back in the Activity file
    doSomeStuff();
}

There are a couple reasons why you might want to programmatically set an OnClickListener. The first is if you ever want to change the behavior of your button while your app is running. You can point your button at another method entirely, or just disable the button by setting an OnClickListener that doesn't do anything.

When you define a listener using the onClick attribute, the view looks for a method with that name only in its host activity. Programmatically setting an OnClickListener allows you to control a button's behavior from somewhere other than its host activity. This will become very relevant when we learn about Fragments, which are basically mini activities, allowing you to build reusable collections of views with their own lifecycle, which can then be assembled into activities. Fragments always need to use OnClickListeners to control their buttons, since they're not Activities, and won't be searched for listeners defined in onClick.

For more commentary on the decision to use an OnClickListener vs onClick, check out this question on Stack Overflow.